﻿using Dapper;
using Dapper.Abstractions;
using DataAccess.Models;

namespace DataAccess.Api.Endpoints.Blog
{
	public class GetList : IEndpoint
	{
		public void MapEndpoint(IEndpointRouteBuilder endpoints)
		{
			endpoints.MapGet("api/blog/dapper/{id}",  async (int id, IDbConnectionFactory dbConnectionFactory) =>
			{
				var connection = await dbConnectionFactory.CreateConnectionAsync();
				var sql = @"
                      SELECT b.*, p.*
                      FROM blogs b
                      LEFT JOIN posts p ON b.Id = p.BlogId
                      WHERE b.Id = @BlogId";

				var blogDict = new Dictionary<int, Models.Blog>();
				var blogs = connection.Query<Models.Blog, Post, Models.Blog>(
					sql,
					(blog, post) =>
					{
						if (!blogDict.TryGetValue(blog.Id, out var blogEntry))
						{
							blogEntry = blog;
							blogEntry.Posts = new List<Post>();
							blogDict.Add(blogEntry.Id, blogEntry);
						}

						blogEntry.Posts.Add(post);
						return blogEntry;
					},
					new { BlogId = id},
					splitOn: "Id" // Posts 表的起始列
				).Distinct().AsList();
				return Results.Ok(blogs);

			})
				.WithName("GetBlogListDapper")
				.WithTags(Tags.Blog);
		}

		public static string StandardizeUrl(string url)
		{
			url = url.ToLower();

			if (!url.StartsWith("http://"))
			{
				url = string.Concat("http://", url);
			}

			return url;
		}
	}
}
